package com.xinshujia.config.authentication.service;

import com.xinshujia.dao.RoleDao;
import com.xinshujia.dao.UserDao;
import com.xinshujia.dto.UserDTO;
import com.xinshujia.entity.UserEntity;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * @author: 野狼上校
 * @since: 2024-08-03 14:03
 * @version: 1.0
 * @descript: 自定义数据库认证实现
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
    private final UserDao userDao;
    private final RoleDao roleDao;

    public MyUserDetailsService(UserDao userDao, RoleDao roleDao) {
        this.userDao = userDao;
        this.roleDao = roleDao;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userDao.loadUserByUsername(username);
        // 是否存在
        if (ObjectUtils.isEmpty(userEntity)) throw new UsernameNotFoundException("用户名不存在");
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(userEntity, userDTO);
        userDTO.setRoles(roleDao.getRolesByUid(userEntity.getId()));
        return userDTO;
    }
}